<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="版本号" prop="versionCode">
        <el-input
          v-model="queryParams.versionCode"
          placeholder="请输入版本号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本名称" prop="versionName">
        <el-input
          v-model="queryParams.versionName"
          placeholder="请输入版本名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="isLatest">
        <el-select v-model="queryParams.isLatest" placeholder="请选择状态" clearable>
          <el-option label="最新版本" :value="1" />
          <el-option label="历史版本" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['version:versions:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['version:versions:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['version:versions:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['version:versions:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="versionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="版本号" align="center" prop="versionCode" />
      <el-table-column label="版本名称" align="center" prop="versionName" />
      <el-table-column label="构建号" align="center" prop="buildNumber" />
      <el-table-column label="文件大小" align="center" prop="fileSize">
        <template #default="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="最低支持版本" align="center" prop="minSupportedVersion" />
      <el-table-column label="是否最新" align="center" prop="isLatest">
        <template #default="scope">
          <el-tag :type="scope.row.isLatest ? 'success' : 'info'">
            {{ scope.row.isLatest ? '最新版本' : '历史版本' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['version:versions:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Star"
            @click="handleSetLatest(scope.row)"
            v-hasPermi="['version:versions:setLatest']"
            v-if="!scope.row.isLatest"
          >设为最新</el-button>
          <el-button
            link
            type="primary"
            icon="Download"
            @click="handleDownload(scope.row)"
          >下载</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['version:versions:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改版本对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="versionRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="版本号" prop="versionCode">
          <el-input 
            v-model="form.versionCode" 
            placeholder="请输入版本号，格式：YYYY.MM.DD.HHmm" 
            :readonly="!form.id"
          >
            <template #append v-if="!form.id">
              <el-button @click="generateVersionInfo" icon="Refresh">重新生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="版本名称" prop="versionName">
          <el-input 
            v-model="form.versionName" 
            placeholder="请输入版本名称，如：v1.2.0" 
            :readonly="!form.id"
          />
        </el-form-item>
        <el-form-item label="构建号" prop="buildNumber">
          <el-input-number 
            v-model="form.buildNumber" 
            :min="1" 
            placeholder="请输入构建号" 
            :readonly="!form.id"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="APK文件" prop="fileName" v-if="!form.id">
          <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".apk"
            :action="uploadFileUrl"
            :headers="uploadHeaders"
            :file-list="fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-error="handleUploadError"
            :on-change="handleFileChange"
            :before-upload="handleBeforeUpload"
            :auto-upload="false"
          >
            <el-button type="primary">选择APK文件</el-button>
            <template #tip>
              <div class="el-upload__tip text-center">
                <span>仅允许导入apk格式文件。</span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="最低支持版本" prop="minSupportedVersion">
          <el-input v-model="form.minSupportedVersion" placeholder="请输入最低支持版本" />
        </el-form-item>
        <el-form-item label="更新说明" prop="updateDescription">
          <el-input v-model="form.updateDescription" type="textarea" placeholder="请输入更新说明" />
        </el-form-item>
        <el-form-item label="是否强制更新" prop="forceUpdate">
          <el-radio-group v-model="form.forceUpdate">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Versions">
import { listVersions, getVersion, delVersion, addVersion, updateVersion, setLatestVersion, uploadApk, getNextVersionInfo } from "@/api/version/versions";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const versionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const fileList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    versionCode: null,
    versionName: null,
    isLatest: null
  },
  rules: {
    versionCode: [
      { required: true, message: "版本号不能为空", trigger: "blur" }
    ],
    versionName: [
      { required: true, message: "版本名称不能为空", trigger: "blur" }
    ],
    buildNumber: [
      { required: true, message: "构建号不能为空", trigger: "blur" }
    ],
    updateDescription: [
      { required: true, message: "更新说明不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 上传参数
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload");
const uploadHeaders = ref({ Authorization: "Bearer " + getToken() });

/** 查询版本列表 */
function getList() {
  loading.value = true;
  listVersions(queryParams.value).then(response => {
    versionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    versionCode: null,
    versionName: null,
    buildNumber: null,
    fileName: null,
    fileSize: null,
    fileMd5: '',  // 确保有默认值
    downloadUrl: null,
    updateDescription: null,
    minSupportedVersion: null,
    forceUpdate: false,
    isLatest: false
  };
  fileList.value = [];
  proxy.resetForm("versionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  generateVersionInfo();
  open.value = true;
  title.value = "添加版本";
}

/** 生成版本信息 */
function generateVersionInfo() {
  // 获取下一个版本信息并自动填充
  getNextVersionInfo().then(response => {
    form.value.versionCode = response.data.versionCode;
    form.value.versionName = response.data.versionName;
    form.value.buildNumber = response.data.buildNumber;
    proxy.$modal.msgSuccess("版本信息已自动生成");
  }).catch(() => {
    // 如果获取失败，使用默认值
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    
    form.value.versionCode = `${year}.${month}.${day}.${hour}${minute}`;
    form.value.versionName = "v1.0.0";
    form.value.buildNumber = 1;
    proxy.$modal.msgWarning("无法获取服务器版本信息，已使用默认值");
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getVersion(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改版本";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["versionRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateVersion(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 新增时需要先上传文件
        if (fileList.value.length > 0) {
          proxy.$refs.uploadRef.submit();
        } else {
          proxy.$modal.msgError("请选择APK文件");
        }
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const versionIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除版本编号为"' + versionIds + '"的数据项？').then(function() {
    return delVersion(versionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 设置最新版本 */
function handleSetLatest(row) {
  proxy.$modal.confirm('是否确认将版本"' + row.versionName + '"设置为最新版本？').then(function() {
    return setLatestVersion(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("设置成功");
  }).catch(() => {});
}

/** 下载按钮操作 */
function handleDownload(row) {
  window.open(row.downloadUrl, '_blank');
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('app/versions/export', {
    ...queryParams.value
  }, `versions_${new Date().getTime()}.xlsx`)
}

// 文件选择变化处理
const handleFileChange = (file, fileListParam) => {
  console.log('文件选择变化:', file, fileListParam);
  fileList.value = fileListParam;
  console.log('当前文件列表长度:', fileList.value.length);
};

// 文件上传中处理
const handleFileUploadProgress = (event, file, fileList) => {
  // 可以在这里显示上传进度
};

// 文件上传成功处理
const handleFileSuccess = (response, file, fileList) => {
  proxy.$modal.closeLoading();
  if (response.code === 200) {
    // 设置文件相关信息（参考ImageUpload和FileUpload组件的处理方式）
    form.value.fileName = response.data.fileName || file.name;
    form.value.fileSize = file.size;
    form.value.downloadUrl = response.data.url;
    
    // 计算文件MD5（如果需要的话，这里简化处理）
    form.value.fileMd5 = response.data.md5 || '';
    
    // 文件上传成功后提交表单
    addVersion(form.value).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList();
      // 清空文件列表
      fileList.value = [];
    }).catch(error => {
      proxy.$modal.msgError("保存版本信息失败：" + (error.msg || error.message));
    });
  } else {
    proxy.$modal.msgError(response.msg || "文件上传失败");
    // 上传失败时清空文件列表
    fileList.value = [];
  }
};

// 文件上传失败处理
const handleUploadError = (error, file, fileList) => {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("文件上传失败，请重试");
  // 上传失败时清空文件列表
  fileList.value = [];
};

// 文件上传前处理
const handleBeforeUpload = (file) => {
  const isAPK = file.type === 'application/vnd.android.package-archive' || file.name.endsWith('.apk');
  const isLt50M = file.size / 1024 / 1024 < 50;

  if (!isAPK) {
    proxy.$modal.msgError('上传文件只能是 APK 格式!');
    return false;
  }
  if (!isLt50M) {
    proxy.$modal.msgError('上传文件大小不能超过 50MB!');
    return false;
  }
  if (file.name.includes(',')) {
    proxy.$modal.msgError('文件名不正确，不能包含英文逗号!');
    return false;
  }
  
  proxy.$modal.loading("正在上传APK文件，请稍候...");
  return true;
};

// 格式化文件大小
function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

getList();
</script>